import express, { Request, Response } from "express";
import multer from "multer";
import path from "path";
import fs from "fs";
import crypto from "crypto";
import sharp from "sharp";
const router = express.Router();
const uploadPath = path.join(__dirname, "../../uploads/images");

// 确保上传目录存在
if (!fs.existsSync(uploadPath)) {
  fs.mkdirSync(uploadPath, { recursive: true });
}

// 计算文件哈希值
const calculateFileHash = (filePath: string): string =>
  crypto.createHash("md5").update(fs.readFileSync(filePath)).digest("hex");

// 配置 Multer 存储方式和文件限制 直接存文件
// const storage = multer.diskStorage({
//   destination: (req, file, cb) => {
//     cb(null, uploadPath); // 文件上传的目标目录
//   },
//   filename: (req, file, cb) => {
//     const hash = crypto
//       .createHash("md5")
//       .update(file.originalname)
//       .digest("hex");
//     cb(null, `${hash}${path.extname(file.originalname)}`);
//   },
// });

// 配置 Multer 使用 memoryStorage 先用内存存储 等待压缩后保存
const storage = multer.memoryStorage();

const upload = multer({
  storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 限制文件大小为 5MB
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|gif|webp/;
    const extname = allowedTypes.test(
      path.extname(file.originalname).toLowerCase()
    );
    const mimetype = allowedTypes.test(file.mimetype);

    if (extname && mimetype) {
      cb(null, true);
    } else {
      cb(new Error("Only images are allowed"));
    }
  },
});

// 单文件上传
router.post("/", upload.single("file"), async (req: Request, res: Response) => {
  if (!req.file) {
    res.status(400).json({ message: "No file uploaded" });
    return;
  }
  const uploadedFileBuffer = req.file.buffer;
  console.log("uploadedFileBuffer", uploadedFileBuffer);
  // 获取上传文件的哈希值
  const uploadedFileHash = crypto
    .createHash("md5")
    .update(req.file.buffer)
    .digest("hex");
  // 压缩图片并保存为 WebP 格式
  const webpFilename = `${uploadedFileHash}.webp`;
  const webpPath = path.join(uploadPath, webpFilename);

  await sharp(uploadedFileBuffer)
    .webp({ quality: 50 }) // 设置压缩质量，90 是较高质量
    .toFile(webpPath);

  const fileUrl = `${req.protocol}://${req.get(
    "host"
  )}/uploads/images/${webpFilename}`;
  res.status(200).json({
    message: "File uploaded successfully",
    url: fileUrl,
  });
});

// 多文件上传
router.post(
  "/array",
  upload.array("files", 5),
  (req: Request, res: Response) => {
    if (!req.files) {
      res.status(400).json({ message: "No files uploaded" });
      return;
    }

    res.status(200).json({
      message: "Files uploaded successfully",
      files: req.files,
    });
  }
);

export default router;
